package app.controllers.customer;

import app.models.gift.Exchange;
import app.models.sys.AuthUsers;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.security.SecurityKit;
import com.jfinal.plugin.activerecord.Record;

import java.util.Date;

/**
 * <p>
 *     礼品兑换
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-06-06 17:42
 * @since JDK 1.6
 */
public class ExchangeController extends BasicController {

    public void index() {
        render("index.ftl");
    }

    public void search() {
        String sn = getPara("sn");
        String query = getPara("query");

        Record record = Exchange.dao.findBySnAndQuery(sn, query);
        if (record == null) {
            renderJson(AjaxMessage.failure("没有查询到礼品兑换记录"));
        } else {
            renderJson(AjaxMessage.ok(record));
        }
    }

    public void receive() {
        long recordId = getParaToLong("recordId", 0l);
        Exchange exchange = Exchange.dao.findById(recordId);
        if (exchange == null) {
            renderJson(AjaxMessage.failure("没有查询到礼品兑换记录"));
        } else {
            exchange.set("receive", true);
            Date now = new Date();

            AuthUsers authUsers = SecurityKit.getLoginUser(getRequest());

            exchange.set("receive_time", now);
            if (authUsers != null) {
                exchange.set("opt_usr", authUsers.get("id"));
            }
            exchange.set("opt_time", now);
            exchange.update();
            renderJson(AjaxMessage.ok("领取成功"));
        }
    }


}
